package com.six.service;

import com.six.domain.dto.AddTableDto;
import com.six.domain.entity.Table;
import com.six.enums.TableStatus;
import com.six.mapper.TableMapper;
import com.six.util.QrCodeUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.zeroturnaround.zip.ByteSource;
import org.zeroturnaround.zip.ZipEntrySource;
import org.zeroturnaround.zip.ZipUtil;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;

@Service

public class TableService {

    private final TableMapper tableMapper;

    @Value("${qr.base-url}")
    private String baseUrl;

    public TableService(TableMapper tableMapper) {
        this.tableMapper = tableMapper;
    }

    public void addTable(AddTableDto dto) {
        Table table = new Table();
        table.setStoreId(dto.getStoreId());
        table.setTableNumber(dto.getTableNumber());
        table.setStatus(TableStatus.FREE.name());
        tableMapper.insert(table);
    }

    public List<Table> getAllTablesByStore(Long storeId) {
        return tableMapper.selectAllTablesByStore(storeId);
    }

    public void updateTableStatus(Long id, String status) {
        try {
            TableStatus.valueOf(status);
        } catch (IllegalArgumentException e) {
            throw new IllegalArgumentException("无效桌台状态：" + status);
        }
        tableMapper.updateStatus(id, status);
    }

    @Transactional
    public byte[] generateTablesWithQr(Long storeId, String prefix, int from, int to) {
        List<ZipEntrySource> entries = new ArrayList<>();
        for (int i = from; i <= to; i++) {
            String tableNumber = prefix + i;
            if (tableMapper.exists(storeId, tableNumber)) {
                continue;
            }
            Table table = new Table();
            table.setStoreId(storeId);
            table.setTableNumber(tableNumber);
            table.setStatus("FREE");
            tableMapper.insert(table);
            String qrContent = baseUrl + "?storeId=" + storeId + "&tableId=" + table.getId();
            byte[] png = QrCodeUtil.asPng(qrContent, 300, 300);
            entries.add(new ByteSource(tableNumber + ".png", png));
        }
        if (entries.isEmpty()) {
            throw new IllegalArgumentException("无新桌台需要生成");
        }
        ByteArrayOutputStream zipOs = new ByteArrayOutputStream();
        ZipUtil.pack(entries.toArray(new ZipEntrySource[0]), zipOs);
        return zipOs.toByteArray();
    }
}